package com.kaiyidiannao.adapter;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.kaiyidiannao.activity.daydaycoupon.DdcShoppingCarActivity;
import com.kaiyidiannao.common.util.ArithUtils;
import com.kaiyidiannao.data.DataCenter;
import com.kaiyidiannao.main.R;
import com.kaiyidiannao.model.bean.DaydayCouponBean;
import com.kaiyidiannao.view.QuantitySelectorView;
import com.kaiyidiannao.view.SpecLinelayout;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

import java.util.ArrayList;
import java.util.Map;

/**
 * Created by david on 14-4-15.
 * 天天惠 - 购物车 - adpter
 */
public class DaydaycouponShoppingCarAdapter extends BaseAdapter {

    private static final String TAG = "DaydaycouponShoppingCarAdapter";
    private ImageLoader imageLoader;
    private Context context;
    private ArrayList<DaydayCouponBean> list;

    private LayoutInflater layoutInflater;

    public DaydaycouponShoppingCarAdapter(Context context, ArrayList<DaydayCouponBean> list) {
        this.context  = context;
        imageLoader = ImageLoader.getInstance();
        imageLoader.init(ImageLoaderConfiguration.createDefault(context));
        this.list = list;
        this.layoutInflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        return list == null ? 0 : list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

        Log.d(TAG, "getview:" + position);

        try {
        ToggleButton toggleButton;//购物车产品是否选择
        QuantitySelectorView quantitySelectorView; // 自定义组件
        TextView key_textview;
        TextView product_title;//产品名称
        TextView product_fare;//产品运费
        TextView product_pay_methods;//产品支付方式
        final TextView product_money;//价格


        final DaydayCouponBean bean = list.get(position);
        View view =  DataCenter.shoppingCarMap.get(new Integer(position));
        if (view == null) {
            convertView = layoutInflater.inflate(R.layout.daydaycoupon_shoppingcar_item, null);
            DataCenter.shoppingCarMap.put(position, convertView);
        } else {
            convertView = DataCenter.shoppingCarMap.get(new Integer(position));
        }


        toggleButton = (ToggleButton) convertView.findViewById(R.id.daydaycoupon_shopping_car_toggle_button);
        quantitySelectorView = (QuantitySelectorView) convertView.findViewById(R.id.daydaycoupon_shopping_car_num);
        product_title = (TextView) convertView.findViewById(R.id.daydaycoupon_shopping_car_product_name);
        key_textview = (TextView) convertView.findViewById(R.id.daydaycoupon_shopping_car_key);
        product_fare = (TextView) convertView.findViewById(R.id.daydaycoupon_shopping_fare);
        product_pay_methods = (TextView) convertView.findViewById(R.id.daydaycoupon_shopping_paymethods);
        product_money = (TextView) convertView.findViewById(R.id.daydaycoupon_shopping_car_price);
        SpecLinelayout specLinelayout = (SpecLinelayout) convertView.findViewById(R.id.daydaycoupon_shopping_car_spec);


        if (bean.getIsCheck() != null && bean.getIsCheck().equals("true")) {
            toggleButton.setChecked(true);
            toggleButton.setSelected(true);
        } else {
            toggleButton.setSelected(false);
            toggleButton.setChecked(false);
        }
        if (bean.getIsCheck() == null) {
            toggleButton.setChecked(true);
            toggleButton.setSelected(true);
        }
        quantitySelectorView.getQuanitityButton().setText("" + bean.getCount());
        int max = 1;
        try {
            max = Integer.parseInt(bean.getAmount());
        } catch (NumberFormatException e) {
            e.printStackTrace();
            max = 0;
        }
        quantitySelectorView.setMAX_COUNT(max);
        product_title.setText("" + bean.getTitle());

        key_textview.setText(bean.getKey());
        product_fare.setText(bean.getFare());
        product_pay_methods.setText(bean.getPayment());

        Object[] specs = bean.getSpecsData();
        Log.d("shoppingcar", specs.length + "");
        specLinelayout.setData(null, specs, false);

        final double price = Double.parseDouble(bean.getPrice());
//        int count = 0;
//        try {
//            count = Integer.parseInt(bean.getCount());
//        } catch (NumberFormatException e) {
//            e.printStackTrace();
//        }

        DdcShoppingCarActivity activity = (DdcShoppingCarActivity) context;
        final TextView countMoneyTextView  = (TextView) activity.findViewById(R.id.daydaycoupon_price_count);


        product_money.setText("" + ArithUtils.toString(price + ""));
        quantitySelectorView.setQuantityChangeListener(new QuantitySelectorView.QuantityChangeListener() {
            @Override
            public void onChanged(int num, boolean isQuanitityButton) {
                //计算总价格
                if (!isQuanitityButton) {
                    countMoneyTextView.setText("" + countSumMoney(DaydaycouponShoppingCarAdapter.this.context, false));
                    Log.d(TAG, "onChanged");
                }
            }
        });

        toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                //计算总价格
                Log.d(TAG, "onCheckedChanged");
                countMoneyTextView.setText("" + countSumMoney(DaydaycouponShoppingCarAdapter.this.context, false));
                if (b) {
                    list.get(position).setIsCheck("true");
                } else {
                    list.get(position).setIsCheck("false");
                }
            }
        });


        quantitySelectorView.getQuanitityButton().performClick();



        } catch (Exception e) {
            e.printStackTrace();
        }
        return convertView;
    }


    /**
     * 计算所有行的总额
     * @param isAllSelect 是否全部选中，true
     * @return
     */
    public String countSumMoney(Context context, boolean isAllSelect) {
        double sumMoney = 0;
        DdcShoppingCarActivity activity = (DdcShoppingCarActivity) context;
        ListView listView = (ListView) activity.findViewById(R.id.daydaycoupon_shopping_car_listview);

        int j = 0;
        for (Map.Entry<Integer, View> entry : DataCenter.shoppingCarMap.entrySet()) {
              View view = entry.getValue();
            if (view != null) {

                ToggleButton toggleButton = (ToggleButton) view.findViewById(R.id.daydaycoupon_shopping_car_toggle_button);
                QuantitySelectorView quantitySelectorView = (QuantitySelectorView) view.findViewById(R.id.daydaycoupon_shopping_car_num);
                double price =  Double.parseDouble(((TextView)view.findViewById(R.id.daydaycoupon_shopping_car_price)).getText().toString());

                Log.d(TAG, "isChecked"+ j + toggleButton.isChecked());
                if (toggleButton.isChecked() || isAllSelect) {

                    TextView textView = (TextView) view.findViewById(R.id.daydaycoupon_shopping_car_price);

                    // 一件商品的总价格
                    double singlePriceCount = ArithUtils.mul(quantitySelectorView.getCount(), price);

                    sumMoney = ArithUtils.round(ArithUtils.add(sumMoney, singlePriceCount), 2);
                }
            }
            j++;
            Log.d(TAG, "sum:"+  j );
        }

        return ArithUtils.toString(sumMoney + "");
    }

}
